package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //设置过滤器的类型 pre routing post error
    @Override
    public String filterType() {
       // return "pre";
        return FilterConstants.PRE_TYPE;//两种方式
    }
    //设置过滤器添加的位置顺序号
    //在默认过滤器第5个中，在上下文对象中添加了serviceid
    @Override
    public int filterOrder() {
        return 6;
    }
    //判断对当前请求是否执行过滤代码
    @Override
    public boolean shouldFilter() {
        /*测试:如果调用商品服务必须登录，其他业务可放行*/
        //得到当前服务id，判断是不是item-service
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        return  "item-service".equalsIgnoreCase(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //http://localhost:3001/item-service/89?token=hfsfjnk
        //接收token参数--通过request对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");
        //判断token
        if (StringUtils.isBlank(token)){
            //没有登录，阻止继续执行
            ctx.setSendZuulResponse(false);
            //向客户端返回响应
            ctx.setResponseStatusCode(400);
            String json = JsonResult.err().
                    code(JsonResult.NOT_LOGIN).
                    msg("not login!!").toString();//转成了json字符串
            ctx.addZuulResponseHeader("Content-Type","application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }
        return null; //当前版本这个返回值没有启用
    }
}
